package io.gitee.xjt2016.modules.sysLog;

import cn.hutool.core.date.SystemClock;
import com.alibaba.fastjson.JSON;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.function.Consumer;

@Aspect
@Component
@Log4j2
public class SysLogAspect {
    private final Consumer<SysLogInfo> consumer;

    public SysLogAspect(Consumer<SysLogInfo> consumer) {
        this.consumer = consumer;
    }

    @Around("@annotation(sysLog)")
    public Object around(ProceedingJoinPoint joinPoint, SysLog sysLog) throws Throwable {
        long beginTime = SystemClock.now();
        //执行方法
        Object result = joinPoint.proceed();
        //执行时长(毫秒)
        long time = SystemClock.now() - beginTime;
        SysLogInfo sysLogEntity = new SysLogInfo();
        if (sysLog != null) {
            //注解上的描述
            sysLogEntity.setOperation(sysLog.value());
        }
        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        sysLogEntity.setMethod(className + "." + methodName + "()");
        //请求的参数
        Object[] args = joinPoint.getArgs();
        if (args.length > 0) {
            String params = JSON.toJSONString(args[0]);
            sysLogEntity.setParams(params);
        }
        //设置IP地址
        sysLogEntity.setIp(IPUtil.getLocalIP());
        //用户名
//        String username = SecurityUtils.getSysUser().getUsername();
//        sysLogEntity.setUsername(username);
        sysLogEntity.setTime(time);
        sysLogEntity.setCreateDate(new Date());
        //保存系统日志
        consumer.accept(sysLogEntity);
        return result;
    }
}